"""工具函数"""
from .models import OperationLog


def get_client_ip(request):
    """获取客户端IP地址"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def log_operation(user, log_type, module, action, request, result=True, error_message=''):
    """记录操作日志"""
    try:
        OperationLog.objects.create(
            user=user if user.is_authenticated else None,
            username=user.username if user.is_authenticated else 'Anonymous',
            log_type=log_type,
            module=module,
            action=action,
            ip_address=get_client_ip(request),
            user_agent=request.META.get('HTTP_USER_AGENT', ''),
            result=result,
            error_message=error_message
        )
    except Exception as e:
        # 记录日志失败不应该影响主流程
        print(f"Failed to log operation: {e}")

